package com.wwf.util;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 远程调用编码类
 * @author wwf
 * @date 2021年01月07日 16:41:18
 */
public class RpcEncode extends MessageToByteEncoder {
    /**
     * 需要编码的原对象
     */
    private Class<?> aClass;
    /**
     * 序列化类
     */
    private Serializer serializer;

    public RpcEncode(Class<?> aClass, Serializer serializer) {
        this.aClass = aClass;
        this.serializer = serializer;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        if(aClass != null && aClass.isInstance(msg)){
            byte[] bytes = serializer.serialize(msg);
            out.writeInt(bytes.length);
            out.writeBytes(bytes);
        }
    }
}
